<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>select、poll、epoll浅析 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="select、poll、epoll浅析"><meta property="og:title" content="select、poll、epoll浅析" />
<meta property="og:description" content="select、poll、epoll浅析" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-06-22T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-06-22T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="select、poll、epoll浅析"/>
<meta name="twitter:description" content="select、poll、epoll浅析"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" /><link rel="prev" href="https://acking-you.github.io/posts/c&#43;&#43;%E5%9F%BA%E7%A1%80%E9%9D%A2%E8%AF%95%E9%A2%981/" /><link rel="next" href="https://acking-you.github.io/posts/logger%E6%97%A5%E5%BF%97%E5%BA%93%E7%9A%84%E5%AE%9E%E7%8E%B0/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "select、poll、epoll浅析",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/selectpollepoll%E6%B5%85%E6%9E%90\/"
        },"genre": "posts","keywords": "select、poll、epoll浅析","wordcount":  3226 ,
        "url": "https:\/\/acking-you.github.io\/posts\/selectpollepoll%E6%B5%85%E6%9E%90\/","datePublished": "2022-06-22T00:00:00+00:00","dateModified": "2022-06-22T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "select、poll、epoll浅析"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center, https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"
        title="select、poll、epoll浅析" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">select、poll、epoll浅析</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/linux%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/"><i class="far fa-folder fa-fw"></i>Linux网络编程</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-06-22">2022-06-22</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 3226 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 7 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#select">select</a>
      <ul>
        <li><a href="#介绍与使用">介绍与使用</a></li>
        <li><a href="#优缺点">优缺点</a></li>
      </ul>
    </li>
    <li><a href="#poll">poll</a>
      <ul>
        <li><a href="#介绍与使用-1">介绍与使用</a></li>
        <li><a href="#优缺点-1">优缺点</a></li>
      </ul>
    </li>
    <li><a href="#epoll">epoll</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><blockquote>
<p>整篇博客的完整示例代码在：<a href="https://github.com/ACking-you/learn_linux/tree/master/learn_net" target="_blank" rel="noopener noreffer">github</a></p>
</blockquote>
<h2 id="select">select</h2>
<h3 id="介绍与使用">介绍与使用</h3>
<p>一、介绍：
select系统调用的目的是：在一段指定时间内，监听用户感兴趣的文件描述符上的可读、可写和异常事件。poll和select应该被归类为这样的系统 调用，它们可以阻塞地同时探测一组支持非阻塞的IO设备，直至某一个设备触发了事件或者超过了指定的等待时间——也就是说它们的职责不是做IO，而是帮助 调用者寻找当前就绪的设备。</p>
<blockquote>
<p>原理图：</p>
</blockquote>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5bfa533860f4465d816c85a6e77b8b88~tplv-k3u1fbpfcp-watermark.image?"
        data-srcset="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5bfa533860f4465d816c85a6e77b8b88~tplv-k3u1fbpfcp-watermark.image?, https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5bfa533860f4465d816c85a6e77b8b88~tplv-k3u1fbpfcp-watermark.image? 1.5x, https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5bfa533860f4465d816c85a6e77b8b88~tplv-k3u1fbpfcp-watermark.image? 2x"
        data-sizes="auto"
        alt="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5bfa533860f4465d816c85a6e77b8b88~tplv-k3u1fbpfcp-watermark.image?"
        title="image.png" /></p>
<p>二、使用</p>
<p>需要的系统调用API如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span> <span class="cpf">&lt;sys/time.h&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;sys/types.h&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;unistd.h&gt;</span><span class="cp">
</span><span class="cp"></span><span class="kt">int</span> <span class="nf">select</span><span class="p">(</span><span class="kt">int</span> <span class="n">nfds</span><span class="p">,</span> <span class="n">fd_set</span> <span class="o">*</span><span class="n">readfds</span><span class="p">,</span> <span class="n">fd_set</span> <span class="o">*</span><span class="n">writefds</span><span class="p">,</span> <span class="n">fd_set</span> <span class="o">*</span><span class="n">exceptfds</span><span class="p">,</span> <span class="k">struct</span> <span class="nc">timeval</span> <span class="o">*</span><span class="n">timeout</span><span class="p">);</span>
</code></pre></div><p>一般经过以下三个过程：</p>
<ol>
<li>定义bitmap结构，就是定义fd_set类型变量，内部实现是一个int数组，整个数组的bit位长 <code>FD_SETSIZE</code>，这个宏默认为1024。</li>
<li>根据文件描述符大小设置bitmap，该步骤调用<code>FD_SET</code>宏进行设置。</li>
<li>调用select函数，并传入bitmap，select内部会根据bitmap上的标记进行轮询，一旦有文件描述符触发事件就将其重新标记到用户态的bitmap里，select除了第一个参数外（第一个参数传入fd的最大值+1），后面连续三个传入的指针参数分别代表：监听读取事件的bitmap、监听写入事件的bitmap、监听异常事件的bitmap，最后一个参数表示延迟时间。</li>
<li>根据bitmap得到已经准备好的文件描述符，并对其执行相应的操作。（Reactor模型</li>
</ol>
<blockquote>
<p>一个文件描述符是否准备就绪，有以下判断：</p>
<p>在网络编程中，</p>
<ol>
<li>下列情况下socket可读：
a) socket内核接收缓冲区的字节数大于或等于其低水位标记SO_RCVLOWAT；
b) socket通信的对方关闭连接，此时该socket可读，但是一旦读该socket，会立即返回0（可以用这个方法判断client端是否断开连接）；
c) 监听socket上有新的连接请求；
d) socket上有未处理的错误。</li>
<li>下列情况下socket可写：
a) socket内核发送缓冲区的可用字节数大于或等于其低水位标记SO_SNDLOWAT；
b) socket的读端关闭，此时该socket可写，一旦对该socket进行操作，该进程会收到SIGPIPE信号；
c) socket使用connect连接成功之后；
d) socket上有未处理的错误。</li>
</ol>
</blockquote>
<p>关键代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"> <span class="c1">//1.定义bitmap结构。  fd_set，是一个bitmap，大小为1024位，是一个长度为1024/32的int数组
</span><span class="c1"></span>    <span class="n">fd_set</span> <span class="n">rset</span><span class="p">;</span>
    <span class="kt">char</span> <span class="n">buffer</span><span class="p">[</span><span class="n">MAXBUF</span><span class="p">];</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">FD_ZERO</span><span class="p">(</span><span class="o">&amp;</span><span class="n">rset</span><span class="p">);</span> <span class="c1">//重置为0
</span><span class="c1"></span>        <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">5</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">FD_SET</span><span class="p">(</span><span class="n">fds</span><span class="p">[</span><span class="n">i</span><span class="p">],</span><span class="o">&amp;</span><span class="n">rset</span><span class="p">);</span>   <span class="c1">//2.根据文件描述符标记bitmap
</span><span class="c1"></span>        <span class="p">}</span>
        <span class="n">puts</span><span class="p">(</span><span class="s">&#34;round again</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">);</span>
        <span class="n">select</span><span class="p">(</span><span class="n">max</span><span class="o">+</span><span class="mi">1</span><span class="p">,</span><span class="o">&amp;</span><span class="n">rset</span><span class="p">,</span><span class="nb">NULL</span><span class="p">,</span><span class="nb">NULL</span><span class="p">,</span><span class="nb">NULL</span><span class="p">);</span> <span class="c1">//3.调用select进行轮询
</span><span class="c1"></span>
        <span class="k">for</span><span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span><span class="nl">fd</span><span class="p">:</span><span class="n">fds</span><span class="p">){</span>
            <span class="k">if</span><span class="p">(</span><span class="n">FD_ISSET</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span><span class="o">&amp;</span><span class="n">rset</span><span class="p">)){</span> <span class="c1">//4.获取已经准备好的描述符进行相应操作
</span><span class="c1"></span>                <span class="n">memset</span><span class="p">(</span><span class="n">buffer</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">MAXBUF</span><span class="p">);</span>
                <span class="n">read</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">buffer</span><span class="p">,</span> <span class="n">MAXBUF</span><span class="p">);</span>
                <span class="n">puts</span><span class="p">(</span><span class="n">buffer</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
</code></pre></div><h3 id="优缺点">优缺点</h3>
<p>从以下三个角度来评析：</p>
<ol>
<li>支持的最大连接数：与 <code>FD_SETSIZE</code> 宏的大小有关，一般为1024。</li>
<li>内核态到用户态的拷贝消耗：非常高，每次select调用都会重新copy一次。</li>
<li>内核态扫描的数据结构：线性扫描，FD剧增后会造成很大的效率问题</li>
</ol>
<p>我们发现上面所说的都是它的各方面特性，同时也体现出了它的缺点。</p>
<p><strong>缺点</strong>：支持的最大文件描述符不够大、每次select调用需要进行大量拷贝且bitmap每次都需要重新set值、内部逻辑是线性扫描不适合大量描述符的情况。</p>
<p>同样在某些条件下，这种简单模型反而会成为优点。</p>
<p><strong>优点</strong>：如果是连接数特别少的情况下，线性扫描反而可能是最优的选择。</p>
<h2 id="poll">poll</h2>
<h3 id="介绍与使用-1">介绍与使用</h3>
<p>一、介绍</p>
<p>poll本质上和select没有区别，它将用户传入的数组拷贝到内核空间，然后查询每个fd对应的设备状态，如果设备就绪则在设备等待队列中加入一项并继续遍历，如果遍历完所有fd后没有发现就绪设备，则挂起当前进程，直到设备就绪或者主动超时，被唤醒后它又要再次遍历fd。</p>
<p>二、使用</p>
<p>经过以下过程：</p>
<ol>
<li>创建pollfd结构，并设置好fd和events。</li>
<li>调用poll函数进行轮询，第一个参数传入需要轮询的pollfd数组，第二个参数传入数组长度，第三个是超时时间。</li>
<li>遍历pollfd数组检测就绪fd并对其进行相应的处理。</li>
</ol>
<blockquote>
<p>代码如下：</p>
</blockquote>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp">    <span class="c1">//1.创建pollfd结构，并设置好要管理的文件描述符以及对应的事件
</span><span class="c1"></span>    <span class="n">pollfd</span> <span class="n">pollfds</span><span class="p">[</span><span class="mi">5</span><span class="p">];</span>
    <span class="k">for</span><span class="p">(</span><span class="k">auto</span><span class="o">&amp;</span> <span class="nl">pollfd</span><span class="p">:</span> <span class="n">pollfds</span><span class="p">){</span>
        <span class="n">pollfd</span><span class="p">.</span><span class="n">fd</span> <span class="o">=</span> <span class="n">accept</span><span class="p">(</span><span class="n">server_fd</span><span class="p">,(</span><span class="n">sockaddr</span><span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">client</span><span class="p">,</span><span class="o">&amp;</span><span class="n">socklen</span><span class="p">);</span>
        <span class="k">if</span><span class="p">(</span><span class="n">pollfd</span><span class="p">.</span><span class="n">fd</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">)</span>
            <span class="n">ERR_EXIT</span><span class="p">(</span><span class="s">&#34;fd accept error&#34;</span><span class="p">);</span>
        <span class="n">pollfd</span><span class="p">.</span><span class="n">events</span> <span class="o">=</span> <span class="n">POLLIN</span><span class="p">;</span> <span class="c1">//检测读取事件
</span><span class="c1"></span>    <span class="p">}</span>
    
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">){</span>
        <span class="n">puts</span><span class="p">(</span><span class="s">&#34;round again&#34;</span><span class="p">);</span>
        <span class="c1">//2.开始进行poll轮询
</span><span class="c1"></span>        <span class="k">if</span><span class="p">(</span><span class="n">poll</span><span class="p">(</span><span class="n">pollfds</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">5000</span><span class="p">)</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">)</span>  <span class="c1">//通过把需要监听的fd拷贝到内核态，如果有事件可读，则设置revents
</span><span class="c1"></span>            <span class="n">ERR_EXIT</span><span class="p">(</span><span class="s">&#34;poll error&#34;</span><span class="p">);</span>
        <span class="c1">//3.遍历pollfd数组检测已经就绪的事件，并执行对应的操作
</span><span class="c1"></span>        <span class="k">for</span><span class="p">(</span><span class="k">auto</span> <span class="o">&amp;</span> <span class="nl">pollfd</span><span class="p">:</span><span class="n">pollfds</span><span class="p">){</span>
            <span class="k">if</span><span class="p">(</span><span class="n">pollfd</span><span class="p">.</span><span class="n">revents</span><span class="o">&amp;</span><span class="n">POLLIN</span><span class="p">){</span>
                <span class="n">pollfd</span><span class="p">.</span><span class="n">revents</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="c1">//重新设置
</span><span class="c1"></span>                <span class="kt">char</span> <span class="n">buffer</span><span class="p">[</span><span class="mi">1024</span><span class="p">]{};</span>
                <span class="kt">int</span> <span class="n">len</span><span class="p">;</span>
                <span class="k">if</span><span class="p">((</span><span class="n">len</span><span class="o">=</span> <span class="n">read</span><span class="p">(</span><span class="n">pollfd</span><span class="p">.</span><span class="n">fd</span><span class="p">,</span><span class="n">buffer</span><span class="p">,</span><span class="mi">1024</span><span class="p">))</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">)</span>
                    <span class="n">ERR_EXIT</span><span class="p">(</span><span class="s">&#34;pollfd read error&#34;</span><span class="p">);</span>
                <span class="k">if</span><span class="p">(</span><span class="n">write</span><span class="p">(</span><span class="n">pollfd</span><span class="p">.</span><span class="n">fd</span><span class="p">,</span><span class="n">buffer</span><span class="p">,</span><span class="n">len</span><span class="p">)</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">){</span>
                    <span class="n">ERR_EXIT</span><span class="p">(</span><span class="s">&#34;pollfd write error&#34;</span><span class="p">);</span>
                <span class="p">}</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
</code></pre></div><h3 id="优缺点-1">优缺点</h3>
<p>三个角度剖析</p>
<ol>
<li>支持的最大连接数：非常多（具体根据系统调度和创建的结构来。</li>
<li>内核态到用户态的拷贝消耗：非常高，每次poll调用都会将整个数组重新从用户态到内核态copy一次，且只支持水平触发。</li>
<li>内核态扫描的数据结构：线性扫描，FD剧增后会造成很大的效率问题。</li>
</ol>
<p><strong>优点</strong>：解决了select因为采取bitmap的连接数限制，且利用的是事件与fd绑定的结构体，用起来会更顺手。</p>
<p><strong>缺点</strong>：仍然没有解决关键的效率问题，同时每次还是通过循环所有结构体来判断事件是否产生的方式来进行，所以本质上和select没有什么不同。</p>
<h2 id="epoll">epoll</h2>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d415f2e59daf4a35b0d0ccd8f122c253~tplv-k3u1fbpfcp-watermark.image?"
        data-srcset="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d415f2e59daf4a35b0d0ccd8f122c253~tplv-k3u1fbpfcp-watermark.image?, https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d415f2e59daf4a35b0d0ccd8f122c253~tplv-k3u1fbpfcp-watermark.image? 1.5x, https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d415f2e59daf4a35b0d0ccd8f122c253~tplv-k3u1fbpfcp-watermark.image? 2x"
        data-sizes="auto"
        alt="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d415f2e59daf4a35b0d0ccd8f122c253~tplv-k3u1fbpfcp-watermark.image?"
        title="image.png" /></p>
<p>前面的讲解都只是为epoll铺路。</p>
<p>具体而言epoll解决了前面的IO复用模型的很多问题。</p>
<p><strong>特点</strong>：</p>
<ol>
<li>IO事件和监视的fd只需要添加一次。<code>epoll_ctl</code></li>
<li>轮询操作是直接将已经就绪的fd赋值到用户态的数组，返回就绪的长度，也就是不需要再遍历所有的fd来判断是否就绪。<code>epoll_wait</code></li>
<li>底层采用红黑树进行轮询，即使有大量fd需要检测，效率也不会太差。</li>
<li>支持水平触发和边缘触发。</li>
</ol>
<p><strong>技术点</strong>：</p>
<ul>
<li>数据结构优化：底层采取红黑树+就绪队列。</li>
<li>零拷贝优化：使用mmap进行内存映射实现内存共享。</li>
<li>多种触发形式优化：支持EPOLLLT和EPOLLET两种触发模式，也就是支持水平触发和边缘触发。</li>
</ul>
<blockquote>
<p>关于水平触发与边缘触发：
水平触发是只要符合触发条件，就会一直触发可读信号，而边缘触发仅仅在状态转变的时候触发一次。</p>
<p>这个和数字电路里面的概念类似：你可以把当前是否符合触发条件想象成一个张图，这张图上有两个状态符合触发条件和不符合触发条件，水平触发是只要状态符合就触发，边缘触发是状态发生改变就触发，而在IO事件里这里的触发状态指的是前面select中讲的socket可读可写等状态。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0cdb8a54e88f48eda80900d2668fb361~tplv-k3u1fbpfcp-watermark.image?"
        data-srcset="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0cdb8a54e88f48eda80900d2668fb361~tplv-k3u1fbpfcp-watermark.image?, https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0cdb8a54e88f48eda80900d2668fb361~tplv-k3u1fbpfcp-watermark.image? 1.5x, https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0cdb8a54e88f48eda80900d2668fb361~tplv-k3u1fbpfcp-watermark.image? 2x"
        data-sizes="auto"
        alt="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0cdb8a54e88f48eda80900d2668fb361~tplv-k3u1fbpfcp-watermark.image?"
        title="image.png" /></p>
</blockquote>
<p><strong>使用</strong>：</p>
<ol>
<li>调用epoll_create创建结构并返回描述符。（需要传入一个参数，Linux 2.6.8后，传入的参数只要大于0即可，在此之前，表示最大的文件描述符</li>
<li>调用epoll_ctl加入需要监听的文件描述符以及对应事件（epoll_event结构体）。（需要传入四个参数：1.需要操作的epoll结构的描述符。2.需要进行的操作。3.需要操作的文件描述符。4.需要加入的结构体。</li>
<li>调用epoll_wait等待事件的到来，并返回就绪的文件描述符数量。（需要传入四个参数：1.需要操作的epoll结构的描述符。2.用于存放就绪的文件描述符的数组。3.数组的最大长度。4.超时时间。）返回值：就绪的文件描述符数量。</li>
</ol>
<p>代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="c1">//1.在内核中创建结构并返回描述符                    epoll_create主要是将内核态的数据结构创建出来并初始化，然后再将它加入进程文件表，得到文件描述符
</span><span class="c1"></span><span class="k">auto</span> <span class="n">epfd</span> <span class="o">=</span> <span class="n">epoll_create</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">//Linux 2.6.8后，传入的参数只要大于0即可，在此之前，表示最大的文件描述符
</span><span class="c1"></span>
<span class="c1">//2.调用epoll_ctl加入需要监听的文件描述符以及对应事件
</span><span class="c1"></span><span class="n">epoll_event</span> <span class="n">evs</span><span class="p">[</span><span class="mi">5</span><span class="p">];</span>
<span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">5</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
    <span class="n">sockaddr_in</span> <span class="n">client</span><span class="p">{};</span>
    <span class="n">socklen_t</span> <span class="n">socklen</span><span class="p">;</span>
    <span class="n">evs</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">data</span><span class="p">.</span><span class="n">fd</span> <span class="o">=</span> <span class="n">accept</span><span class="p">(</span><span class="n">server_fd</span><span class="p">,(</span><span class="n">sockaddr</span><span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">client</span><span class="p">,</span><span class="o">&amp;</span><span class="n">socklen</span><span class="p">);</span>
    <span class="n">evs</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">events</span> <span class="o">=</span> <span class="n">EPOLLIN</span><span class="p">;</span> <span class="c1">//需要读取的事件
</span><span class="c1"></span>    <span class="k">if</span><span class="p">(</span><span class="n">epoll_ctl</span><span class="p">(</span><span class="n">epfd</span><span class="p">,</span><span class="n">EPOLL_CTL_ADD</span><span class="p">,</span><span class="n">evs</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">data</span><span class="p">.</span><span class="n">fd</span><span class="p">,</span><span class="o">&amp;</span><span class="n">evs</span><span class="p">[</span><span class="n">i</span><span class="p">])</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">)</span>  <span class="c1">//添加或删除内核数据结构中指定的文件描述符对应的结点
</span><span class="c1"></span>        <span class="n">ERR_EXIT</span><span class="p">(</span><span class="s">&#34;epoll_ctl&#34;</span><span class="p">);</span>
<span class="p">}</span>


<span class="k">while</span><span class="p">(</span><span class="mi">1</span><span class="p">){</span>
    <span class="n">puts</span><span class="p">(</span><span class="s">&#34;round again&#34;</span><span class="p">);</span>
    <span class="c1">//3.调用epoll_wait等待事件的到来，并返回就绪的文件描述符数量
</span><span class="c1"></span>    <span class="c1">//查询就绪队列，并将已经ok的文件描述符，从左到右写入数组，返回写入的长度，返回-1表示轮询超时
</span><span class="c1"></span>    <span class="k">auto</span> <span class="n">nfds</span> <span class="o">=</span> <span class="n">epoll_wait</span><span class="p">(</span><span class="n">epfd</span><span class="p">,</span><span class="n">evs</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">10000</span><span class="p">);</span> <span class="c1">//查询就绪队列，然后把就绪到位的文件描述符和对应的情况写入用户空间中的数组
</span><span class="c1"></span>    <span class="c1">//遍历数组，执行最后的动作
</span><span class="c1"></span>    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="n">nfds</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="kt">char</span> <span class="n">buffer</span><span class="p">[</span><span class="mi">1024</span><span class="p">]{};</span>
        <span class="kt">int</span> <span class="n">len</span><span class="p">{};</span>
        <span class="k">if</span><span class="p">((</span><span class="n">len</span> <span class="o">=</span> <span class="n">read</span><span class="p">(</span><span class="n">evs</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">data</span><span class="p">.</span><span class="n">fd</span><span class="p">,</span><span class="n">buffer</span><span class="p">,</span><span class="mi">1024</span><span class="p">))</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">){</span>
            <span class="n">ERR_LOG</span><span class="p">(</span><span class="s">&#34;read error&#34;</span><span class="p">);</span>
        <span class="p">}</span><span class="k">else</span><span class="p">{</span>
            <span class="k">if</span><span class="p">(</span><span class="n">write</span><span class="p">(</span><span class="n">evs</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">data</span><span class="p">.</span><span class="n">fd</span><span class="p">,</span><span class="n">buffer</span><span class="p">,</span><span class="n">len</span><span class="p">)</span><span class="o">&lt;</span><span class="mi">0</span><span class="p">){</span>
                <span class="n">ERR_LOG</span><span class="p">(</span><span class="s">&#34;write error&#34;</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div><p>对epoll实现原理更为具体的描述有以下链接：</p>
<p><a href="https://www.zhihu.com/question/486578358#:~:text=%E5%A6%82%E6%9E%9C%20epoll%20%E7%AE%A1%E7%90%86%E7%9A%84%20socket,%E5%9B%BA%E5%AE%9A%E7%9A%84%E8%AF%9D%EF%BC%8C%E5%9C%A8%E6%95%B0%E6%8D%AE%E6%94%B6%E5%8F%91%E7%9A%84%E4%BA%8B%E4%BB%B6%E7%AE%A1%E7%90%86%E8%BF%87%E7%A8%8B%E4%B8%AD%E5%85%B6%E5%AE%9E%E7%BA%A2%E9%BB%91%E6%A0%91%E6%98%AF%E6%B2%A1%E6%9C%89%E8%B5%B7%E4%BD%9C%E7%94%A8%E7%9A%84%E3%80%82%20%E5%86%85%E6%A0%B8%E5%9C%A8socket%E4%B8%8A%E6%94%B6%E5%88%B0%E6%95%B0%E6%8D%AE%E5%8C%85%E4%BB%A5%E5%90%8E%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%9B%B4%E6%8E%A5%E6%89%BE%E5%88%B0%20epitem%20%28epoll%20item%29%EF%BC%8C%E5%B9%B6%E6%8A%8A%E5%AE%83%E6%8F%92%E5%85%A5%E5%88%B0%E5%B0%B1%E7%BB%AA%E9%98%9F%E5%88%97%E9%87%8C%EF%BC%8C%E7%84%B6%E5%90%8E%E7%AD%89%E7%94%A8%E6%88%B7%E8%BF%9B%E7%A8%8B%E6%8A%8A%E4%BA%8B%E4%BB%B6%E5%8F%96%E8%B5%B0%E3%80%82" target="_blank" rel="noopener noreffer">epoll 原理是如何实现的？</a></p>
<p><a href="https://mp.weixin.qq.com/s/OmRdUgO1guMX76EdZn11UQ" target="_blank" rel="noopener noreffer">图解 | 深入揭秘 epoll 是如何实现 IO 多路复用的！</a></p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/selectpollepoll%E6%B5%85%E6%9E%90/">select、poll、epoll浅析</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-06-22</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析" data-hashtags="select、poll、epoll浅析"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-hashtag="select、poll、epoll浅析"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析" data-image="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析" data-description="select、poll、epoll浅析"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析" data-description="select、poll、epoll浅析"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/selectpollepoll%E6%B5%85%E6%9E%90/" data-title="select、poll、epoll浅析"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/c&#43;&#43;%E5%9F%BA%E7%A1%80%E9%9D%A2%E8%AF%95%E9%A2%981/" class="prev" rel="prev" title="C&#43;&#43;面试题1"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/logger%E6%97%A5%E5%BF%97%E5%BA%93%E7%9A%84%E5%AE%9E%E7%8E%B0/" class="next" rel="next" title="Logger日志库的实现">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
